#lang racket

(require ffi/unsafe
         ffi/unsafe/define)
(require file/resource)

(require "primitives.rkt")


(define (set-proxy-windows! port)
  ;[DllImport("wininet.dll")]
  (define-ffi-definer define-wininet (ffi-lib "wininet"))
  
  ;public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
  (define-wininet InternetSetOptionW
    (_fun _int _int _int _int -> _bool))
  (write-resource "HKEY_CURRENT_USER"
                  "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\ProxyEnable"
                  1)
  (write-resource "HKEY_CURRENT_USER"
                  "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\ProxyServer"
                  (string-append "127.0.0.1:" (number->string port)))
  
  ;InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
  (InternetSetOptionW
   0
   39
   0
   0)
  ;InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
  (InternetSetOptionW
   0
   37
   0
   0)
  )

(define (clear-proxy-windows!)
  ;[DllImport("wininet.dll")]
  (define-ffi-definer define-wininet (ffi-lib "wininet"))
  
  ;public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
  (define-wininet InternetSetOptionW
    (_fun _int _int _int _int -> _bool))
  (write-resource "HKEY_CURRENT_USER"
                  "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\ProxyEnable"
                  0)
  (write-resource "HKEY_CURRENT_USER"
                  "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\ProxyServer"
                  "" )
  
  ;InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
  (InternetSetOptionW
   0
   39
   0
   0)
  ;InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
  (InternetSetOptionW
   0
   37
   0
   0)
  )

(define (set-proxy! port)
  (match (system-type)
    ['unix (process (string-append "sh ./unix/set.sh " (number->string port)))]
    ['windows (set-proxy-windows! port)]
    ['macosx (system (string-append "bash ./macosx/start.sh " (number->string port)))]))

(define (clear-proxy!)
  (match (system-type)
    ['unix (process (string-append "sh ./unix/unset.sh"))]
    ['windows (clear-proxy-windows!)]
    ['macosx (system (string-append "sh ./macosx/stop.sh "))]))

(provide set-proxy! clear-proxy!)